﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using libManagedMessageSystem;
using System.Runtime.InteropServices;

namespace ManagedEchoServer
{
    class Packet : Message
    {
        public Int32 a;
        public float b;
        public String s;
        public UInt32 c;

        public override void Read(NetStream stream)
        {
            a = stream.ReadInt32();
            b = stream.ReadFloat();
            s = stream.ReadString();
            c = stream.ReadUInt32();
        }

        public override void Write(NetStream stream)
        {
            stream.WriteInt32(a);
            stream.WriteFloat(b);
            stream.WriteString(s);
            stream.WriteUInt32(c);
        }
    }
    class Program
    {
        class TestMessageHandler:IMessageHandler
        {
            public virtual void OnLost()
            {
                Console.WriteLine("OnLost");
            }

            public virtual void OnMsg(MessageChannel mc,UInt16 nDispatchId,UInt16 nMessageId, NetStream ns)
            {
                switch(nMessageId)
                {
                    case 1:
                        {
                            break;
                        }
                    case 2:
                        {
                            Packet p = new Packet();
                            p.Read(ns);
                            mc.Dispatch(nDispatchId, nMessageId, ns);
                            break;
                        }
                }
            }
        }

        static void OnAccept(MessageChannel mc)
        {
            mc.Open(new TestMessageHandler());
            Console.WriteLine("OnAccept");
        }

        unsafe static void Main(string[] args)
        {
            MessageSystem ms = new MessageSystem();
            try
            {
                ms.ListenLocalSystem("127.0.0.1", 5000, OnAccept);
                while(true)
                    ms.Poll(1000);
            }
            catch(System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.ReadLine();
        }
    }
}
